<?php
/**
 * Created by PhpStorm.
 * User: ye
 * Date: 2017/11/21
 * Time: 下午9:12
 */

namespace App\Http\Controllers;


use App\Book;
use App\BookUser;
use App\Common\BookSearch;
use Illuminate\Http\Request;

class KeywordController extends CheckController {

    public function index(Request $request) {
        $perpage = $request->input('perpage', 10);
        $next_cursor = $request->input('next_cursor', 1);

        $keywords = Book::groupBy('keyword')
            ->selectRaw('title, keyword, count(*) as count')
//            ->skip(($next_cursor -1)* $perpage)
//            ->take($perpage)
            ->get();

        $bookSearch = new BookSearch($this->userinfo);
        $books = $bookSearch->search($request->all());

        $multiplied = $keywords->map(function ($item, $key) {
            return [
                'keyword' => empty($item->keyword) ? $item->title : $item->keyword,
                'count' => $item->count
            ];
        });

        $all_keywords = $multiplied->all();

        return $this->output(
            200,
            '获取所有 keywords 成功',
            [
                'keywords' => $all_keywords,
                'books' => $books,
                'has_more' => count($all_keywords) == $perpage,
                'next_cursor' => $next_cursor + 1
            ]
        );
    }

    public function store(Request $request) {
        $keyword = $request->input('keyword', false);
        $id = $request->input('id', false);

        if($keyword === false || $id === false) {
            return $this->output(400, '缺少传参');
        }

        $book = BookUser::find($id);

        if ($book && $book->user_id == $this->userinfo->id) {
            $keywords = $book->keywords;

            if (in_array($keyword, $keywords)) {
                return $this->output(201, '已存在该图书标签');
            } else {
                $keywords[] = $keyword;
                $book->keywords = $keywords;
                $book->save();
                return $this->output(200, '保存成功', ['keywords' => $keywords]);
            }

        }
        return $this->output(401, '找不到图书');
    }

    public function destroy(Request $request, $id) {
        $keyword = $request->input('keyword', false);
//        $id = $request->input('id', false);

        if($keyword === false || $id === false) {
            return $this->output(400, '缺少传参');
        }

        $book = BookUser::find($id);

        if ($book && $book->user_id == $this->userinfo->id) {
            $keywords = $book->keywords;
            if (($key = array_search($keyword, $keywords)) !== false) {
                array_splice($keywords, $key, 1);
                $book->keywords = $keywords;
                $book->save();
                return $this->output(200, '移除成功', ['keywords' => $keywords]);
            } else {
                return $this->output(201, '不存在该图书标签');
            }
        }
        return $this->output(401, '找不到图书');
    }

}